package com.bw.gmall.realtime.dws.app;

import cn.hutool.core.collection.ListUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bw.gmall.realtime.common.base.BaseApp;
import com.bw.gmall.realtime.common.bean.TradeOrderBean;
import com.bw.gmall.realtime.common.constant.Constant;
import com.bw.gmall.realtime.common.util.DateFormatUtil;
import com.bw.gmall.realtime.common.util.DorisMapFunction;
import com.bw.gmall.realtime.common.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.ArrayList;

/**
 * @projectName: gmalll2206
 * @package: com.bw.gmall.realtime.dws.app
 * @className: DwsTradeOrderWindow
 * @author: DuanYu
 * @description: TODO
 * @date: 2025/3/5 14:00
 * @version: 1.0
 */

public class DwsTradeOrderWindow extends BaseApp {
    public static void main(String[] args) {
        new DwsTradeOrderWindow().start(Constant.TOPIC_DWD_TRADE_ORDER_DETAIL, Constant.DWS_TRADE_ORDER_WINDOW, 4, 10028);
    }

    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> dataStreamSource) {
        SingleOutputStreamOperator<JSONObject> etlStream = getEtlStream(dataStreamSource);
//        etlStream.print();
        SingleOutputStreamOperator<JSONObject> wmStream = getTs(etlStream);
        KeyedStream<JSONObject, String> keyedStream = keyedStream(wmStream);
        SingleOutputStreamOperator<TradeOrderBean> processStream = getProcess(keyedStream);
        SingleOutputStreamOperator<TradeOrderBean> result = getProcess(processStream);
//        processStream.print();
//        result.print();
        result.map(new DorisMapFunction<>()).sinkTo(FlinkSinkUtil.getDorisSink(Constant.DWS_TRADE_ORDER_WINDOW));
    }

    private static SingleOutputStreamOperator<TradeOrderBean> getProcess(SingleOutputStreamOperator<TradeOrderBean> processStream) {
        return processStream.windowAll(TumblingEventTimeWindows.of(Time.seconds(3))).process(new ProcessAllWindowFunction<TradeOrderBean, TradeOrderBean, TimeWindow>() {
            @Override
            public void process(ProcessAllWindowFunction<TradeOrderBean, TradeOrderBean, TimeWindow>.Context context, Iterable<TradeOrderBean> iterable, Collector<TradeOrderBean> collector) throws Exception {
                ArrayList<TradeOrderBean> tradeOrderBeans = ListUtil.toList(iterable);
                long onuc = tradeOrderBeans.stream().mapToLong(e -> e.getOrderNewUserCount()).sum();
                long ouuc = tradeOrderBeans.stream().mapToLong(e -> e.getOrderUniqueUserCount()).sum();
                String start = DateFormatUtil.tsToDateTime(context.window().getStart());
                String end = DateFormatUtil.tsToDateTime(context.window().getEnd());
                String curDate = DateFormatUtil.tsToDate(System.currentTimeMillis());
                TradeOrderBean next = tradeOrderBeans.iterator().next();
                collector.collect(TradeOrderBean.builder()
                        .stt(start)
                        .edt(end)
                        .orderNewUserCount(onuc)
                        .orderUniqueUserCount(ouuc)
                        .curDate(curDate)
                        .ts(next.getTs())
                        .build());
            }
        });
    }

    private static SingleOutputStreamOperator<TradeOrderBean> getProcess(KeyedStream<JSONObject, String> keyedStream) {
        return keyedStream.process(new KeyedProcessFunction<String, JSONObject, TradeOrderBean>() {
            private ValueState<String> valueState;

            @Override
            public void open(Configuration parameters) throws Exception {
                ValueStateDescriptor<String> lastDate = new ValueStateDescriptor<>("last_date", String.class);
                valueState = getRuntimeContext().getState(lastDate);
            }

            @Override
            public void processElement(JSONObject jsonObject, KeyedProcessFunction<String, JSONObject, TradeOrderBean>.Context context, Collector<TradeOrderBean> collector) throws Exception {
                Long ts = jsonObject.getLong("ts") * 1000;
                String curDate = DateFormatUtil.tsToDate(ts);
                String value = valueState.value();
                long orderUu = 0L;
                long orderNew = 0L;
                if (!curDate.equals(value)) {
                    orderUu = 1L;
                    valueState.update(curDate);
                }
                if (value == null) {
                    orderNew = 1L;
                }
                if (orderUu == 1) {
                    collector.collect(TradeOrderBean.builder()
                            .orderUniqueUserCount(orderUu)
                            .orderNewUserCount(orderNew)
                            .ts(ts)
                            .build());
                }

            }
        });
    }


    private static KeyedStream<JSONObject, String> keyedStream(SingleOutputStreamOperator<JSONObject> wmStream) {
        return wmStream.keyBy(new KeySelector<JSONObject, String>() {
            @Override
            public String getKey(JSONObject jsonObject) throws Exception {
                return jsonObject.getString("user_id");
            }
        });
    }

    private static SingleOutputStreamOperator<JSONObject> getTs(SingleOutputStreamOperator<JSONObject> etlStream) {
        return etlStream.assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(5)).withTimestampAssigner(new SerializableTimestampAssigner<JSONObject>() {
            @Override
            public long extractTimestamp(JSONObject jsonObject, long l) {
                return jsonObject.getLong("ts") * 1000;
            }
        }));
    }

    private static SingleOutputStreamOperator<JSONObject> getEtlStream(DataStreamSource<String> dataStreamSource) {
        return dataStreamSource.flatMap(new RichFlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String s, Collector<JSONObject> collector) throws Exception {
                JSONObject jsonObject = JSONObject.parseObject(s);
                String user_id = jsonObject.getString("user_id");
                String ts = jsonObject.getString("ts");
                if (user_id != null && ts != null) {
                    collector.collect(jsonObject);
                }
            }
        });
    }
}
